package com.sun.servlet;

import com.alibaba.fastjson.JSON;
import com.sun.dao.BookDao;
import com.sun.dao.ReaderDao;
import com.sun.domain.Book;
import com.sun.domain.Reader;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author SunRui
 * @description book servlet
 * @date 2024/7/4 21:06
 */
@WebServlet(urlPatterns = "/BookServlet.action")
public class BookServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(ReaderServlet.class);
    InputStream resource = Resources.getResourceAsStream("mybatisConfig.xml");
    //获取session工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);

    public BookServlet() throws IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BookDao bookDao = sqlSession.getMapper(BookDao.class);
        String opr = req.getParameter("opr");
        String jsonString = null;
        HttpSession session = req.getSession();
        String str = null;
        switch (opr) {
            case "bookLoad":
                String text = req.getParameter("text");
                int categoryId = Integer.parseInt(req.getParameter("categoryId"));
                //图书列表加载
                logger.debug("图书列表加载传输的数据为：" + text + ";" + categoryId);
                List<Book> bookList = bookDao.getList(text, categoryId);
                sqlSession.close();
                System.out.println("bookList:" + bookList);
                jsonString = JSON.toJSONString(bookList);
                resp.getWriter().write(jsonString);
                break;
            case "bookDetail":
                //书籍详情
                int id = Integer.parseInt(req.getParameter("bookId"));
                Book book = bookDao.getBook(id);
                logger.debug("获取的书籍信息:" + book.toString());
                sqlSession.close();
                jsonString = JSON.toJSONString(book);
                resp.getWriter().write(jsonString);
                break;
            case "addTS":
                //暂存架
                String code = req.getParameter("code");
                List<String> codeArray = (List<String>) session.getAttribute("codeArray");
                if (codeArray == null) {
                    List<String> codes = new ArrayList<>();
                    session.setAttribute("codeArray", codes);
                }
                codeArray = (List<String>) session.getAttribute("codeArray");
                if (codeArray.contains(code)) {
                    logger.debug("已存在：" + code);
                    str = "have";
                } else {
                    codeArray.add(code);
                    logger.debug("目前暂存架有：" + codeArray.toString());
                    str = "ok";
                }
                sqlSession.close();
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
            case "borrowTsShow":
                // 获取暂存架数据
                List<String> codeArrays = (List<String>) session.getAttribute("codeArray");
                List<Book> bookTs = new ArrayList<>();
                if (codeArrays == null || codeArrays.isEmpty()) {
                    // 暂存架没有数据，可以返回提示信息或者执行其他操作
                   logger.debug("暂存架没有数据");
                } else {
                    bookTs = new ArrayList<>();
                    for (String codes : codeArrays) {
                        Book books = bookDao.bookTs(codes);
                        bookTs.add(books);
                    }
                }
                sqlSession.close();
                jsonString = JSON.toJSONString(bookTs);
                logger.debug("暂存架数据缓存为：" + jsonString);
                resp.getWriter().write(jsonString);
                break;
            case "eliminateBookTs":
                //接收传回要清除的暂存架图书id
                String elBookTs = req.getParameter("bookIds");
                if (elBookTs != null && elBookTs.length() > 2) {
                    elBookTs = elBookTs.substring(1, elBookTs.length() - 1);
                    String[] eliminateBookTs = elBookTs.split(",");
                    List<String> elBootTsId = new ArrayList<>();
                    for (String bookId : eliminateBookTs) {
                        elBootTsId.add(bookId.replace("\"", ""));
                    }
                    //获取缓存架数据进行清除操作
                    List<String> eliminateCodeArray = (List<String>) session.getAttribute("codeArray");
                    logger.debug("elBootTsId:" + elBootTsId.toString());
                    logger.debug("eliminateCodeArray:" + eliminateCodeArray.toString());
                    if (eliminateCodeArray != null) {
                        for (String bookId : elBootTsId) {
                            if (eliminateCodeArray.contains(bookId)) {
                                eliminateCodeArray.remove(bookId);
                            }
                        }
                        session.setAttribute("codeArray", eliminateCodeArray);
                        str = "ok";
                    }
                    logger.debug("清除结束(codeArray)：" + (List<String>) session.getAttribute("codeArray"));
                } else {
                    //处理elBookTs为空或长度不足的情况
                    logger.debug("elBookTs为空或长度不足");
                }
                sqlSession.close();
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;


        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

}
